#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import hmac
import hashlib
import base64
import json
from urllib.parse import urlparse, quote
import requests
import urllib.request
import urllib.parse
import re
from bs4 import BeautifulSoup
import os
import subprocess


class SSHConnection:
    def sshconn(self):
        tm = time.strftime("%Y%m%d", time.localtime())
        dir = "/data/release/sosotest_files/reports/%s/" % tm
        os.chdir(dir)
        oo = os.listdir(".")
        list1 = []
        for i in oo:
            r = ".+?HTTP_TASK_14_(.+?)\.html"
            rs = re.findall(r, i)
            if rs != []:
                list1.append(rs[0])
        mx = "HTTP_TASK_14_" + max(list1) + ".html"
        p = subprocess.run(["find", ".", "-name", f"*{mx}"], stdout=subprocess.PIPE)
        out = p.stdout.decode("utf8").strip("./")
        print(out)
        fileDir = os.path.join(dir, out)
        print(fileDir)
        return fileDir

    def run(self):
        fileDir = self.sshconn()
        p = fileDir.split("/")
        url03 = "http://10.5.1.54:8000/" + p[4] + "/" + p[5] + "/" + p[6]
        print(url03)
        clean_url = urllib.parse.unquote(url03).strip()
        res = requests.get(url=clean_url)
        soup = BeautifulSoup(res.text, "html.parser")
        href = soup.find_all("tr", attrs={"name": "resultTr"})
        str_rs = ""
        http_success = []
        http_error = []
        summary_info_divs = soup.find_all("div", id="summary_info")
        summary_info_div = summary_info_divs[0]
        task_name = summary_info_div.find_all("p")[3].text.strip()
        Task_name = task_name.replace("任务：", "")
        for i in range(len(href)):
            id = "listshow_interface_%s" % i
            f = href[i].find_all("div", id="listshow_interface_%s" % i)[0]
            r = re.compile('<tr class="result_pop"><td>断言结果(.+?)\n')
            s = r.findall(str(f))
            r1 = re.compile("^<caption>(.+?)</caption", re.M)
            s1 = r1.findall(str(f))[0].split("请求：")
            if s != []:
                if "全部断言通过" in s[0]:
                    http_success.append(id)
                    continue
                else:
                    r2 = re.compile(".+?断言结果.+?实际结果:{(.+?)}")
                    r_err = r2.findall(str(f))
                    s2 = "请求结果：%s" % r_err[0]
                    s4 = "请求地址:" + s1[1]
                    s3 = "接口名称：" + s1[0] + "\n" + s4 + "\n" + s2 + "\n"
                    http_error.append(s3)
                    str_rs = str_rs + s3
                    if "登陆" in s1[0]:
                        break
            else:
                r2 = re.compile(".+?断言结果</td>(.+?)</tr>")
                r_err = r2.findall(str(f))
                s2 = "请求结果：%s" % r_err[0]
                s4 = "请求地址:" + s1[1]
                s3 = (
                    "\n"
                    + "接口名称："
                    + s1[0]
                    + "\n"
                    + "\n"
                    + s4
                    + "\n"
                    + "\n"
                    + s2
                    + "\n"
                    + "\n"
                )
                str_rs = str_rs + s3
                if "登陆" in s1[0]:
                    break
        print("CasePASS:", len(http_success))
        print("CaseFAIL:", len(http_error))
        count = len(http_success) + len(http_error)
        print("CaseTOTAL:", count)
        if str_rs:
            secret = (
                "SEC07bc9038af5d4373024513f65641084d9dedee0c1607d8e52d18e64f4924efe0"
            )
            url = "https://oapi.dingtalk.com/robot/send?access_token=102357cff29ce2b0ac01e6965637a1c7cd09949b36fd8871ca3db0ae43bc6198"
            timestamp = int(time.time() * 1000)
            print(timestamp)
            secret_enc = secret.encode("utf-8")
            string_to_sign = "{}\n{}".format(timestamp, secret)
            string_to_sign_enc = string_to_sign.encode("utf-8")
            hmac_code = hmac.new(
                secret_enc, string_to_sign_enc, digestmod=hashlib.sha256
            ).digest()
            sign = quote(base64.b64encode(hmac_code))
            print(sign)

            web_url = url + "&timestamp={}&sign={}".format(timestamp, sign)
            webhook_url = str(web_url)
            print(webhook_url)

            nowtime = time.strftime("%Y.%m.%d %H:%M:%S ", time.localtime(time.time()))

            header = {"Content-Type": "application/json", "Charset": "UTF-8"}
            data = {
                "msgtype": "markdown",
                "markdown": {
                    "title": "线上巡检告警",
                    "text": "\n![](https://raw.githubusercontent.com/Andyzrp/Andyzrp.github.io/gh-pages/report/hight.jpg)\n"
                    "\n ## 执行项目：%s\n"
                    "\n测试结果：执行失败\n"
                    "\n统计详情：总计接口:%s   成功：%s   失败：%s\n"
                    "\n执行时间：%s\n"
                    "\n[测试报告链接](%s)\n"
                    "\n错误信息：%s\n"
                    "\n![](https://github.com/Andyzrp/Andyzrp.github.io/blob/gh-pages/report/zttest.png?raw=true)\n"
                    "\n@18720918322"
                    % (
                        Task_name,
                        count,
                        len(http_success),
                        len(http_error),
                        nowtime,
                        url03,
                        str(str_rs),
                    ),
                },
                "at": {"atMobiles": ["18720918322"], "isAtAll": False},
            }

            send_data = json.dumps(data)
            print(send_data)
            send_data = send_data.encode("utf-8")
            request = urllib.request.Request(
                url=webhook_url, data=send_data, headers=header
            )
            with urllib.request.urlopen(request) as opener:
                print(opener.read().decode("utf-8"))
        else:
            print("执行成功")


if __name__ == "__main__":
    test = SSHConnection()
    test.run()
